import React, { useState } from 'react'
import { 
  Settings, 
  Mic, 
  Globe, 
  Zap, 
  Volume2, 
  Smartphone, 
  Trash2,
  Download,
  Upload,
  RefreshCw,
  Info
} from 'lucide-react'
import { useVoiceStore } from '../stores/voiceStore'
import { useDeviceStore } from '../stores/deviceStore'
import { useSocketStore } from '../stores/socketStore'
import speechService from '../services/speechService'
import { VoiceSettings } from '../stores/voiceStore'

const SettingsPage: React.FC = () => {
  const [showAdvanced, setShowAdvanced] = useState(false)

  const {
    language,
    settings,
    voiceHistory,
    setLanguage,
    updateSettings,
    clearHistory,
    getStats
  } = useVoiceStore()

  const {
    deviceName,
    capabilities,
    updateDeviceName,
    resetDevice,
    getDeviceStats
  } = useDeviceStore()

  const { 
    isConnected, 
    connectionError,
    forceReconnect 
  } = useSocketStore()

  const stats = getStats()
  const deviceStats = getDeviceStats()
  const supportedLanguages = speechService.getSupportedLanguages()

  // 更新语言设置
  const handleLanguageChange = (newLanguage: string) => {
    setLanguage(newLanguage)
    speechService.updateConfig({ language: newLanguage })
  }

  // 更新语音设置
  const handleSettingChange = (key: keyof VoiceSettings, value: boolean) => {
    const newSettings = { ...settings, [key]: value }
    updateSettings(newSettings)
    
    // 更新语音识别配置
    if (['continuous', 'interimResults', 'maxAlternatives'].includes(key)) {
      speechService.updateConfig({ [key]: value })
    }
  }

  // 导出数据
  const handleExportData = () => {
    const data = {
      version: '1.0',
      timestamp: new Date().toISOString(),
      device: deviceStats,
      settings: {
        language,
        voiceSettings: settings
      },
      history: voiceHistory,
      stats
    }
    
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    
    const a = document.createElement('a')
    a.href = url
    a.download = `smartinput-data-${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  // 导入数据
  const handleImportData = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (!file) return

    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const data = JSON.parse(e.target?.result as string)
        
        if (data.settings?.language) {
          handleLanguageChange(data.settings.language)
        }
        
        if (data.settings?.voiceSettings) {
          updateSettings(data.settings.voiceSettings)
        }
        
        alert('数据导入成功')
      } catch (error) {
        alert('数据导入失败：文件格式错误')
      }
    }
    reader.readAsText(file)
  }

  // 重置所有设置
  const handleResetAll = () => {
    if (confirm('确定要重置所有设置吗？这将清除所有数据和配对信息。')) {
      clearHistory()
      resetDevice()
      updateSettings({
        autoSend: true,
        continuous: false,
        interimResults: true,
        maxAlternatives: 1,
        noiseReduction: true,
        echoCancellation: true,
        autoGainControl: true
      })
      setLanguage('zh-CN')
      alert('设置已重置')
    }
  }

  return (
    <div className="min-h-screen bg-gray-50 p-4">
      <div className="max-w-md mx-auto space-y-4">
        <div className="flex items-center space-x-3">
          <Settings className="w-6 h-6 text-gray-700" />
          <h1 className="text-2xl font-bold">设置</h1>
        </div>

        {/* 设备设置 */}
        <div className="card">
          <h2 className="card-title"><Smartphone className="w-5 h-5 mr-2" />设备设置</h2>
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <label htmlFor="deviceName" className="text-sm font-medium">设备名称</label>
              <input 
                id="deviceName"
                type="text"
                value={deviceName}
                onChange={(e) => updateDeviceName(e.target.value)}
                className="input input-sm w-48 text-right"
              />
            </div>
            <div className="text-xs text-gray-500">
              这个名称将显示在配对的电脑上。
            </div>
          </div>
        </div>

        {/* 语音识别设置 */}
        <div className="card">
          <h2 className="card-title"><Mic className="w-5 h-5 mr-2" />语音识别</h2>
          <div className="space-y-4">
            <div>
              <label htmlFor="language" className="text-sm font-medium">识别语言</label>
              <select 
                id="language" 
                value={language}
                onChange={(e) => handleLanguageChange(e.target.value)}
                className="select w-full mt-1"
              >
                {supportedLanguages.map(lang => (
                  <option key={lang.code} value={lang.code}>{lang.name}</option>
                ))}
              </select>
            </div>

            <div className="flex items-center justify-between">
              <label htmlFor="autoSend" className="text-sm font-medium">自动发送识别结果</label>
              <input 
                id="autoSend"
                type="checkbox"
                checked={settings.autoSend}
                onChange={(e) => handleSettingChange('autoSend', e.target.checked)}
                className="toggle toggle-primary"
              />
            </div>
          </div>
        </div>
        
        {/* 高级设置 */}
        <div className="card">
          <button onClick={() => setShowAdvanced(!showAdvanced)} className="w-full text-left">
            <h2 className="card-title flex justify-between items-center">
              <span><Zap className="w-5 h-5 mr-2 inline" />高级选项</span>
              <span className={`transform transition-transform ${showAdvanced ? 'rotate-180' : ''}`}>
                ▼
              </span>
            </h2>
          </button>

          {showAdvanced && (
            <div className="mt-4 space-y-4 pt-4 border-t">
              <div className="flex items-center justify-between">
                <label htmlFor="continuous" className="text-sm font-medium">连续识别</label>
                <input 
                  id="continuous"
                  type="checkbox"
                  checked={settings.continuous}
                  onChange={(e) => handleSettingChange('continuous', e.target.checked)}
                  className="toggle"
                />
              </div>
              <div className="flex items-center justify-between">
                <label htmlFor="interimResults" className="text-sm font-medium">显示临时结果</label>
                <input 
                  id="interimResults"
                  type="checkbox"
                  checked={settings.interimResults}
                  onChange={(e) => handleSettingChange('interimResults', e.target.checked)}
                  className="toggle"
                />
              </div>
              <div className="flex items-center justify-between">
                <label htmlFor="noiseReduction" className="text-sm font-medium">降噪</label>
                <input 
                  id="noiseReduction"
                  type="checkbox"
                  checked={settings.noiseReduction}
                  onChange={(e) => handleSettingChange('noiseReduction', e.target.checked)}
                  className="toggle"
                />
              </div>
              <div className="flex items-center justify-between">
                <label htmlFor="echoCancellation" className="text-sm font-medium">回声消除</label>
                <input 
                  id="echoCancellation"
                  type="checkbox"
                  checked={settings.echoCancellation}
                  onChange={(e) => handleSettingChange('echoCancellation', e.target.checked)}
                  className="toggle"
                />
              </div>
            </div>
          )}
        </div>

        {/* 数据管理 */}
        <div className="card">
          <h2 className="card-title"><Download className="w-5 h-5 mr-2" />数据管理</h2>
          <div className="grid grid-cols-2 gap-2">
            <button onClick={handleExportData} className="btn btn-secondary">
              <Download className="w-4 h-4 mr-1" />
              导出数据
            </button>
            <label htmlFor="import-data" className="btn btn-secondary cursor-pointer">
              <Upload className="w-4 h-4 mr-1" />
              导入数据
            </label>
            <input id="import-data" type="file" accept=".json" className="hidden" onChange={handleImportData} />
          </div>
        </div>

        {/* 关于与信息 */}
        <div className="card">
          <h2 className="card-title"><Info className="w-5 h-5 mr-2" />关于与信息</h2>
          <div className="text-xs text-gray-600 space-y-2">
            <div className="flex justify-between"><span>应用版本:</span> <span>v1.0.0</span></div>
            <div className="flex justify-between">
              <span>连接状态:</span>
              <span className={isConnected ? 'text-green-600' : 'text-red-600'}>
                {isConnected ? '已连接' : `未连接 ${connectionError ? `(${connectionError})` : ''}`}
              </span>
            </div>
            <div className="flex justify-between"><span>设备ID:</span> <span className="truncate">{deviceStats.deviceId}</span></div>
            <div className="flex justify-between"><span>历史记录条数:</span> <span>{stats.historyCount}</span></div>
            <div className="flex justify-between">
              <span>支持的特性:</span> 
              <span>{deviceStats.supportedFeatures.join(', ')}</span>
            </div>
            <div className="pt-2">
              <button onClick={forceReconnect} className="btn btn-sm btn-secondary w-full">
                <RefreshCw className="w-4 h-4 mr-1" />
                强制重连
              </button>
            </div>
          </div>
        </div>

        {/* 危险区域 */}
        <div className="card border-red-200 bg-red-50">
          <h2 className="card-title text-red-800"><Trash2 className="w-5 h-5 mr-2" />危险操作</h2>
          <div className="grid grid-cols-2 gap-2">
            <button onClick={clearHistory} className="btn btn-danger">
              清空历史记录
            </button>
            <button onClick={handleResetAll} className="btn btn-danger">
              重置所有设置
            </button>
          </div>
          <p className="text-xs text-red-600 mt-2">
            这些操作无法撤销，请谨慎使用。
          </p>
        </div>
      </div>
    </div>
  )
}

export default SettingsPage 